import { message } from 'antd'

export default {
    namespace: 'websocket',
    state: {
        ws: null
    },
    reducers: {
        connectWS(_, { id, onMessage, onOpen }) {
            const ws = new WebSocket(`ws://localhost:8080/myServer/${id}`)
            if (onOpen instanceof Function) {
                ws.onopen = onOpen
            } else {
                ws.onopen = () => {
                    // message.success(`已连接至服务器`)
                }
            }
            if (onMessage instanceof Function) {
                ws.onmessage = onmessage
            }
            ws.onerror = () => {
                message.error('webSocket出错了')
            }
            return { ws }
        },
        disconnectWS(state) {
            const { ws } = state
            if (ws instanceof WebSocket) {
                ws.close()
                message.success('已断开连接')
            }
            return {
                ws: null
            }
        }
    }
}